#!/bin/bash

# Set mctpi2c link up and assign local address.
localEid=8
busNum=9
maxRetries=5
retryInterval=1

retry_command() {

    command="$1"
    retries=0

    while [ $retries -lt $maxRetries ]; do
        if bash -c "$command"; then
            return 0
        else
            retries=$((retries + 1))
            echo "Retry $retries/$maxRetries: Command failed. Retrying in $retryInterval seconds..."
            sleep $retryInterval
        fi
    done

    return 1
}

# Retry mctp link command
if ! retry_command "mctp link set mctpi2c${busNum} up"; then
    echo "Failed to set mctp link after $maxRetries attempts."
    exit 1
fi

# Check if local EID is already set
mctpOutput=$(mctp address show)
if echo "$mctpOutput" | grep -q "mctpi2c${busNum}"; then
    echo "mctpi2c${busNum} local EID already set"
else
    # Retry mctp addr add command
    if ! retry_command "mctp addr add ${localEid} dev mctpi2c${busNum}"; then
        echo "Failed to add mctp address after $maxRetries attempts."
        exit 1
    fi
fi
echo "mctpi2c${busNum} local EID set to ${localEid}"
exit 0